package com.hyg.lib_base.base;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hyg.lib_base.Net.NetworkChangeEvent;
import com.hyg.lib_base.Net.NetworkUtils;
import com.hyg.lib_base.lisener.PermissionListener;
import com.hyg.lib_base.mainUtils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MyBaseActivity extends AppCompatActivity {

    protected boolean mCheckNetWork = true; //默认检查网络状态
    //    View mTipView = null;
//    WindowManager mWindowManager;
    public static final String TAG = "lgb";
    public static final String CrashTAG = "CrashTAG";
    public static final String ErrorTAG = "ErrorTAG";
    private int TypeStyle = 0;  //正常，斜体

    public PermissionListener listener;
   static String[] needPermissins;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setScreenRoate(true);
        EventBus.getDefault().register(this);
        ARouter.getInstance().inject(this);
        ARouter.openLog();     // 打印日志
    }

//    @Override
//    public Resources getResources() {
//        Resources res = super.getResources();
//        Configuration config = res.getConfiguration();
//        config.fontScale = 1.1f; //1 设置正常字体大小的倍数
//        res.updateConfiguration(config, res.getDisplayMetrics());
//        return res;
//    }

    /**
     * 设置屏幕横竖屏切换
     *
     * @param screenRoate true  竖屏     false  横屏
     */
    private void setScreenRoate(Boolean screenRoate) {
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O && Build.VERSION.SDK_INT != Build.VERSION_CODES.O_MR1) {
            if (screenRoate) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置竖屏模式
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        }
    }

    public void showToast(String message) {
        Toast.makeText(getApplication(), message, Toast.LENGTH_SHORT).show();
    }

    public void ToIntent(String activityUrl, boolean isFinish) {
        ARouter.getInstance().build(activityUrl).navigation();
        startActivityAnim();
        if (isFinish) finish();
    }

    public void back_finish_activity(boolean isFinish) {
        if (Utils.isFastClick()) {
            return;
        }
        startActivityAnim();
        if (isFinish) finish();
    }

    public void ToMessageIntent(String activityUrl, int type, Bundle bundle, boolean isFinish) {
        ARouter.getInstance().build(activityUrl).withInt("type", type).withBundle("bundle", bundle).navigation();
        startActivityAnim();
        if (isFinish) finish();
    }

    public void ToResultIntent(Intent it_msg, int requesCode) {
        startActivityForResult(it_msg, requesCode);
        startActivityAnim();
    }

    public void BackResultIntent(int resultCode, Intent it_msg) {
        setResult(resultCode, it_msg);
        startActivityAnim();
        finish();
    }

    public void BackResultIntent(String activityUrl, int resultCode) {
        ARouter.getInstance().build(activityUrl).navigation(this, resultCode);
        startActivityAnim();
        this.finish();
    }


    public void startActivityAnim() {
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        //在无网络情况下打开APP时，系统不会发送网络状况变更的Intent，需要自己手动检查
        hasNetWork(NetworkUtils.isConnected(this.getApplication()));
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void finish() {
        super.finish();
        //当提示View被动态添加后直接关闭页面会导致该View内存溢出，所以需要在finish时移除
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetworkChangeEvent(NetworkChangeEvent event) {
        hasNetWork(event.isConnected);
    }

    private void hasNetWork(boolean has) {
    }

    private static long lastConnectTime;
    public static int unLock = 0; //通过连点 ，进行解锁

    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastConnectTime < 500) {
            lastConnectTime = time;
            unLock++;
            return true;
        } else {
            lastConnectTime = time;
            unLock = 0;
            return false;
        }
    }

    public boolean UINetWork(boolean has) {
        if (isCheckNetWork()) {
            Log.d(TAG, "onReceive: 检查当前UI网络has " + has);
            //            if (has) {
            //                if (pDialog.isShowing())
            //                    pDialog.dismiss();
            //            } else {
            //                if (!pDialog.isShowing() && !this.isFinishing())
            //                    pDialog.show();
            //            }
        }
        return has;
    }

    public void setCheckNetWork(boolean checkNetWork) {
        mCheckNetWork = checkNetWork;
    }

    public boolean isCheckNetWork() {
        return mCheckNetWork;
    }




    public static final int PERMISSON_REQUESTCODE = 88;


    /**
     * description: 获取相应权限
     *
     * @author visitant
     * @time 2020/12/15 17:03
     */
    public void getPermissions(String[] permissions, PermissionListener listener) {
        this.listener = listener;
        this.needPermissins = permissions;
        List<String> list = new ArrayList<>();
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                list.add(permission);
            }
        }
        if (list.size() > 0) {
            String[] noPermisson = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                noPermisson[i] = list.get(i);
            }
            ActivityCompat.requestPermissions(this, noPermisson, PERMISSON_REQUESTCODE);
        } else if (listener != null) {
            int[] result = new int[needPermissins.length];
            for (int i = 0; i < result.length; i++) {
                result[i] = PackageManager.PERMISSION_GRANTED;
            }
            listener.onResult(result);
        }
    }

    /**
     * 申请权限结果的回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            int[] result = new int[needPermissins.length];
            for (int i = 0; i < result.length; i++) {
                result[i] = 0;
            }
            for (int i = 0; i < permissions.length; i++) {
                for (int j = 0; j < needPermissins.length; j++) {
                    if (permissions[i].equalsIgnoreCase(needPermissins[j])) {
                        result[j] = paramArrayOfInt[i];
                        break;
                    }
                }
            }
            if (listener != null) {
                listener.onResult(result);
//                needPermissins = null;
            }
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isHideInput(view, ev)) {
                HideSoftInput(view.getWindowToken());
                view.clearFocus();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 判定是否需要隐藏
     */
    private boolean isHideInput(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 隐藏软键盘
     */
    private void HideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


}